import React, { Fragment, Component } from "react";
import { download } from '../utils'

class DownloadButton extends Component {
  constructor() {
    super();
  }

  onClick() {
    const data = this.articles.map(article => {
      const info = article.querySelector('.article-info')
      const title = info.querySelector('h3 a')
      const time = info.querySelector('.article-meta time')
      const star = info.querySelector('.article-meta .like-count')
      return {
        title: title.textContent,
        time: time.textContent,
        timestamp: parseInt(time.dataset.timestamp) * 1000,
        star: star.textContent
      }
    })
    console.log(data)
    download('articles.json', JSON.stringify(data, null, 4))
  }

  get articles() {
    const collection = document.getElementById("articles-collection")
    return [
      ...collection.querySelectorAll('.article-item')
    ]
  }

  render() {
    return (
      <Fragment>
        <button type="button" className="c-article-comments-form__submit js-submit-comment"
          style={{margin: 0,padding: 10,fontSize: 20,height: 'auto',width: 'fit-content'}}
          onClick={this.onClick.bind(this)}
        >
          Extract Articles
        </button>
      </Fragment>
    );
  }
}

export default DownloadButton;
